#include "sphere.h"
#define EPSILON 0.0001

Sphere::Sphere(d_Vec3f c, float r, Material *mat)
{
	center = c;
	radius = r;
	material = mat;
}

bool Sphere::intersect(const Ray &r, Hit &h, float tmin)
{
	d_Vec3f R0 = center-r.getOrigin();
	bool inside = false;

	if(dot(R0,R0)<radius*radius)
		inside=true;

	float tp = dot(R0, r.getDirection());

	if(tp < tmin)
		return false;

	float dd = dot(R0,R0)-tp*tp;

	if(dd > radius*radius && !inside)
		return false;
	float tmptmp = radius*radius-dd;
	if(tmptmp<0)
		tmptmp = -tmptmp;
	float tprime = sqrt(tmptmp);
	float t;

	if(inside)
	{
		t = tp+tprime; 
	}
	else
	{
		t = tp-tprime;
	}

	if(((t < h.getT())&&(t>=tmin))||(inside))
	{
		d_Vec3f normal = r.pointAtParameter(t)-center;
		normal = norm(normal);
		h.set(t, material, normal);
		return true;
	}
		
	return false;
}

bool Sphere::inside(d_Vec3f point)
{
	if(len(point-center)<= radius)
		return true;
	else
		return false;
}
